/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */
import React, {Component} from 'react';
import {
	Alert,
	DeviceEventEmitter,
	Dimensions,
	StyleSheet,
	Text,
	TextInput,
	TouchableHighlight,
	View,
} from 'react-native';
// 在你需要用到的页面，导入
import DateUtil from './component/DateUtil';
import DigitUtil from './component/DigitUtil';
import Toast from '@remobile/react-native-toast';
import BluetoothSerial from 'react-native-bluetooth-serial';
import BackImage from './component/BackImage';
import axiosInstance from './utils/request';

const {ESC} = BluetoothSerial;


//屏幕信息
var dimensions = require('Dimensions');
//获取屏幕的宽度
const WIN_WIDTH = Dimensions.get('window').width;
var width = WIN_WIDTH/2;

export default class PrepayScene extends Component {


	constructor(props){
		super(props);
		const { params } = this.props.route;
		this.props.navigation.setOptions({
			title:'用户缴费'
		})

		this.state={
			isEnabled: false,
			devices: [],
			discovering: false,
			animationType: 'none',//none slide fade
			modalVisible: false,//模态场景是否可见
			transparent: false,//是否透明显示

			counter:0,//已连接设备数
			isOpenBlueM: false, // 是否打开蓝牙
			isShowActivityIndicator: false, // 是否显示加载提示
			doesConnected: false, // 是否连接
			isConnecting: false, // 是否正常连接,用于点击已配对设备
			isPairingBlueMDevice: false, // 是否正在配对设备
			connectTipsText: '正在连接',
			currentConnectDevice: {}, // 当前点击连接的设备
			pairDeviceData: [], // 已经配对的设备
			unPairDeviceArray: [], // 未配对的设备
			connectedID: null, // 连接的ID

			name:global.user.userData.name,
			custCode:params.custCode,
			custName:"",
			currMonth:params.currMonth,
			tel:"",
			address: "",
			payfee:"",
			balance: 0.00,
			arrears: 0.00,
			surplus:0.00,
		};
	}

	componentWillMount(){
		Promise.all([
		  BluetoothSerial.isEnabled(),
		  BluetoothSerial.list()
		])
		.then((values) => {
		  const [ isEnabled, devices ] = values
		  this.setState({ isEnabled, devices })
		})

		BluetoothSerial.on('bluetoothEnabled', () => Toast.showShortBottom('Bluetooth enabled'))
		BluetoothSerial.on('bluetoothDisabled', () => Toast.showShortBottom('Bluetooth disabled'))
		BluetoothSerial.on('error', (err) => console.log(`Error: ${err.message}`))
		BluetoothSerial.on('connectionLost', () => {
		if (this.state.device) {
			Toast.showShortBottom(`Connection to device ${this.state.device.name} has been lost`)
		}
			this.setState({ connected: false })
		})
	}

	componentDidMount() {
        // 判断蓝牙是否可用
        BluetoothSerial.isEnabled().then(result => {
          this.setState({
            isEnabled: result
          });
        }).catch((err)=>{

		})

		let number=0;
		this.toggleBluetooth(true);
		this.discoverUnpaired();
		BluetoothSerial.list().then(devices => {
			if(devices.length==0){
				Alert.alert('提示','蓝牙未配对，请在蓝牙设置中进行配对！');
				return;
			}
			//遍历已配对设备，
			devices.map((device, i) => {
				if (this.state.isConnecting) return
				BluetoothSerial.isConnected()
				.then((results) => {
					if(results){
						number++;
						this.setState({
							counter:number
						});
						Toast.showShortCenter('蓝牙已连接');
					}
				})
				.catch((err) => {
					console.log('isConnected：'+err);
				})
			});
        }).catch((err) => {
			console.log('BluetoothSerial.list()：'+err);
		})

		//收到监听
		this.listener = DeviceEventEmitter.addListener('print', (params) => {
			//收到监听后想做的事情
			if(params.payMode=='2'){
				this.printBill();
			}
		})

		const data = {
			custCode:this.state.custCode,
			pageVO:{
				sort:'',
				order:''
			}
	  	};

		this.getData(data);
    }

	componentWillUnmount() {
		this.listener.remove();
	};

	getData(data){
		let url=global.server.url+'/custPrepay/selectCustCost';
		axiosInstance({
		  method: 'post',
		  url: url,
		  data: data
		})
        .then(res => {
			let custInfoVo=res.custInfoVo;
			let arrears=res.arrears;
			this.setState({
				custName:custInfoVo.custName,
				address:custInfoVo.address,
				custTypeName:custInfoVo.custTypeName,
				balance:custInfoVo.money,
				tel:custInfoVo.tel,
				arrears:arrears
			});
        }).catch(err => {
        	Toast.show("网络异常，请稍后再试！"+err);
        })
	}

	payTips(){
		let custCode = this.state.custCode;
		let custName = this.state.custName;
		let balance = parseFloat(this.state.balance).toFixed(2);
		let payfee=parseFloat(this.state.payfee).toFixed(2);
		let arrears=parseFloat(this.state.arrears).toFixed(2);

		if (payfee==0 || typeof(payfee)=="undefined" || payfee == null || isNaN(payfee)) {
			Toast.showShortBottom('缴费金额不能为空或为零！');
			return;
		}

		if(this.state.counter==0){
			Alert.alert('提示','请在蓝牙设置中连接已配对设备！');
			return;
		}

		const data = {
			custName:custName,
			custCode:custCode,
			balance:balance,
			source:"app",
			payfee:payfee,
			arrears:arrears,
			memo:"APP缴费，用户余额大于欠费"
	  	};

		Alert.alert(
            '提示', //提示标题
            '确定要交费'+this.state.payfee+'元吗？', //提示内容
            [
                {
                 	text: '确定',
				  	onPress: ()=> this.pay(data)
				},
				{
					text: '取消',
					onPress: () => console.log('点击取消')
				}
            ] //按钮集合
        )
	}

	pay(data){
        let url=global.server.url+'/payment/pay';
		axiosInstance({
		  method: 'post',
		  url: url,
		  data: data
		}).then(res => {
        	if(res.success){
				Alert.alert(
					'提示', //提示标题
					'交费成功，是否打印票据？', //提示内容
					[
						{
							text: '确定',
							onPress: ()=> this.printBill()
						},
						{
							text: '取消',
							onPress: () => console.log('取消打印')
						}
					] //按钮集合
				)
			}else{
				Toast.showShortBottom('缴费失败！');
			}
        })
        .catch(err => {
        	Toast.showShortBottom("缴费时发生异常，请联系系统管理员:"+err);
        })
    }

	changeMoney(payfee){
		//去掉以零开头的数字
		payfee=payfee.replace(/\b(0+)/gi,"");

		payfee = payfee.replace(/[^\d.]/g, "");
        //必须保证第一位为数字而不是.
        payfee = payfee.replace(/^\./g, "");
        //保证只有出现一个.而没有多个.
        payfee = payfee.replace(/\.{2,}/g, ".");
        //保证.只出现一次，而不能出现两次以上
        payfee = payfee.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");

		let surplus=0;
		let arrears=parseFloat(this.state.arrears);
		let balance=parseFloat(this.state.balance);

		if((payfee+balance)>=arrears){
			surplus=(Number(payfee)+parseFloat(balance))-parseFloat(arrears);
		}

		this.setState({
			surplus:surplus.toFixed(2),
			payfee:payfee
		});
	}

	printBill(){

		const Config = {
          wordNumber: 32
        }

        ESC.setConfig(Config)

        // 打印初始化
        ESC.init()
        ESC.alignCenter()
        ESC.fontBold()
        ESC.printAndNewLine()
        ESC.text('南坤高山水厂')
        ESC.printAndNewLine()

        ESC.text('收款收据')
        ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.init()
        ESC.text('用户名称：'+this.state.custName)
		ESC.printAndNewLine()

        ESC.text('用户户号：'+this.state.custCode)
		ESC.printAndNewLine()

        ESC.text('详细地址：'+this.state.address)
		ESC.printAndNewLine()

		ESC.text('应收金额:'+this.state.arrears)
		ESC.printAndNewLine()

		ESC.text('缴费金额:'+this.state.payfee)
		ESC.printAndNewLine()

		ESC.text('金额大写:'+DigitUtil.digitUppercase(this.state.payfee))
		ESC.printAndNewLine()

		ESC.text('上期结余：'+this.state.balance)
		ESC.printAndNewLine()

		ESC.text('本次结余:'+this.state.surplus)
		ESC.printAndNewLine()

        ESC.text('抢修电话:13976071522 13976072444')

        ESC.printAndNewLine()
        ESC.alignRight()
        ESC.text('收费员：'+this.state.name)
        ESC.printAndNewLine()

		ESC.alignRight()
        ESC.text('收费日期：'+DateUtil.myformatter(new Date()))
        ESC.printAndNewLine()

        ESC.printAndNewLine()
        ESC.printAndNewLine()
        ESC.printAndNewLine()
        ESC.printAndNewLine()

        ESC.sound()
        ESC.init()
	}

	//扫码支付
  	payQrCode(){
		let custCode = this.state.custCode;
		let custName = this.state.custName;
		let balance = parseFloat(this.state.balance).toFixed(2);
		let payfee=parseFloat(this.state.payfee).toFixed(2);
		let arrears=parseFloat(this.state.arrears).toFixed(2);
		let currMonth=this.state.currMonth;

		if (payfee==0 || typeof(payfee)=="undefined" || payfee == null || isNaN(payfee)) {
			Toast.showShortBottom('缴费金额不能为空或为零！');
			return;
		}

		const data = {
			custName:custName,
			custCode:custCode,
			balance:balance,
			source:"app",
			payfee:payfee,
			arrears:arrears
	  	};
		this.props.navigation.navigate('WxPayScene',data)
	}

	gotoCostHis(){
		let custCode = this.state.custCode;
		let custName = this.state.custName;
		DeviceEventEmitter.emit('Tab', {});
		this.props.navigation.navigate('CustInfoEditScene', {custCode:custCode,custName:custName,tabIndex:1});
	}
	/**
   	* [android]
   	* enable bluetooth on device
   	*/
  	enable () {
    	BluetoothSerial.enable()
    	.then((res) => this.setState({ isEnabled: true }))
    	.catch((err) => Toast.showShortBottom(err.message))
  	}

  	/**
   	 * [android]
     * disable bluetooth on device
   */
	disable () {
   		BluetoothSerial.disable()
    	.then((res) => this.setState({ isEnabled: false }))
    	.catch((err) => Toast.showShortBottom(err.message))
  	}

	/**
	* [android]
	* toggle bluetooth
	*/
	toggleBluetooth (value) {
		if (value === true) {
		  this.enable()
		} else {
		  this.disable()
		}
	}

	/**
	* [android]
	* Discover unpaired devices, works only in android
	*/
	 discoverUnpaired () {
		if (this.state.discovering) {
		  return false
		} else {
		  this.setState({ discovering: true })
		  BluetoothSerial.discoverUnpairedDevices()
		  .then((unpairedDevices) => {
			this.setState({ unpairedDevices, discovering: false })
		  })
		  .catch((err) => Toast.showShortBottom(err.message))
		}
	}

	render() {
		return (
			<View style={styles.container}>
				<View style={styles.items}>
					<Text style={styles.textStyle}>客户编号:</Text>
					<Text style={{fontSize: 18,marginRight: 5,width:width-110}}>{this.state.custCode}</Text>

					<Text style={styles.textStyle}>客户名称:</Text>
					<Text style={{fontSize: 18,marginRight: 5}}>{this.state.custName}</Text>
				</View>

				<View style={styles.items}>
					<Text style={styles.textStyle}>详细地址:</Text>
					<Text style={{fontSize: 18,marginRight: 5}}>{this.state.address}</Text>
				</View>

				<View style={styles.items}>
					<Text style={styles.textStyle}>应收金额:</Text>
					<Text style={{fontSize: 18,marginRight: 5,width:width-120}}>{this.state.arrears}</Text>

					<Text style={styles.textStyle}>移动电话:</Text>
					<Text style={{fontSize: 18,marginRight: 5}}>{this.state.tel}</Text>
				</View>

				<View style={styles.items}>
					<Text style={styles.textStyle}>上期结余:</Text>
					<Text style={{fontSize: 18,marginRight: 5,width:width-120}}>{this.state.balance}</Text>
					<Text style={styles.textStyle}>本次结余:</Text>
					<Text style={{fontSize: 18,marginRight: 5}}>{this.state.surplus}</Text>
				</View>
				<View style={styles.items}>
					<Text style={styles.textStyle}>本次缴费:</Text>
					<TextInput
						underlineColorAndroid="gray"
						placeholder="请输入缴费金额"
						autoFocus={true}
						keyboardType='numeric'
						clearButtonMode="while-editing"
						style={{flex:0.9}}
						value={this.state.payfee+''}
						onChangeText={(text) => this.changeMoney(text)}>
					</TextInput>
				</View>
				<View style={styles.items}>
					<TouchableHighlight
							style={styles.saveBtn}
							underlayColor='transparent'
							onPress={() => this.payTips()}>
						<Text style={styles.saveText}>现金交费</Text>
					</TouchableHighlight>
					<TouchableHighlight
							style={styles.saveBtn}
							underlayColor='transparent'
							onPress={() => this.printBill()}>
						<Text style={styles.saveText}>打印</Text>
					</TouchableHighlight>
					<TouchableHighlight
							style={styles.saveBtn}
							underlayColor='transparent'
							onPress={() => this.payQrCode()}>
						<Text style={styles.saveText}>扫码支付</Text>
					</TouchableHighlight>
					<TouchableHighlight
							style={styles.saveBtn}
							underlayColor='transparent'
							onPress={() => this.gotoCostHis()}>
						<Text style={styles.saveText}>缴费记录</Text>
					</TouchableHighlight>
				</View>
			</View>
		)
    }
}

var width = WIN_WIDTH/2;
const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    items: {
        flexDirection: 'row',
        alignItems: 'center',
        margin: 5
    },
    textStyle: {
        fontSize: 18,
        color: 'black',
		marginLeft: 5,
        marginRight: 5
    },
    saveBtn: {
        height: 35,
		width:70,
        backgroundColor: 'green',
        margin: 10,
        justifyContent: 'center',
		borderRadius:5
    },
    saveText: {
        fontSize: 15,
        alignSelf: 'center',
        color: '#FFF'
    },
	button: {
		margin:5,
		backgroundColor: 'white',
		padding: 15,
		borderBottomWidth: StyleSheet.hairlineWidth,
		borderBottomColor: '#cdcdcd',
	},
	modalContainer:{
		flex: 1,
		justifyContent: 'center',
		padding: 40,
  	},
	innerContainer: {
		borderRadius: 10,
		alignItems: 'center',
    },
	tips:{
		textAlign: 'center',
		marginBottom: 5,
		fontSize: 14
	},
	settingStyle:{
        flexDirection:'row',
        justifyContent:'space-between',
        width:width - 10,

    },
});


